/*
 * 创建日期 2005-10-5
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.vanda.report.element;

import java.util.List;

import com.vanda.report.ReportException;
import com.vanda.report.ReportInnerData;
import com.vanda.report.ReportUtils;
import com.vanda.report.Validation;

/**
 * 循环处理标签 <br>
 * <p>
 * 
 * @author eagle <br>
 * @version Version 1.00 <br>
 */
public class ForElement extends BeanElement {
	/** 指定开始位置，默认为0，即从第一个开始 */
	private int start;
	/** 指定结束位置，默认为0，结束位置=property.size-end */ 
	private int end;

	public void validator() throws ReportException {
		Validation.checkRequired("ForElement", "property", super.getProperty());
		Validation.checkRequired("ForElement", "start", start, -1);
		Validation.checkRequired("ForElement", "end", end, -1);
	}

	/**
	 * 标签执行方法，递归执行
	 * @param obj
	 */
	public void execute(Object obj) throws ReportException {
		ReportInnerData reportData = (ReportInnerData) obj;
		String property = super.getProperty();

		try {
			//取得List或数组实例
			Object objs = getListObject(reportData, property);
			
			if(objs != null){
				//循环执行
				executeMulti(reportData, objs,start,ReportUtils.getListSize(objs)-end);
			}
		} catch (ReportException e) {
			throw e;
		} catch (Exception e) {
			throw new ReportException(e);
		}

	}


	protected void executeMulti(ReportInnerData reportData, Object objs,int nStart,int nEnd)
		throws ReportException {
		if (objs instanceof List) {
			List listObjs = (List) objs;

			for (int i = nStart; i < nEnd; i++) {
				executeSingle(reportData, listObjs.get(i));
			}
		} else {
			Object[] objArray = (Object[]) objs;
			for (int i = nStart; i < nEnd; i++) {
				executeSingle(reportData, objArray[i]);
			}
		}
	}

	private void executeSingle(ReportInnerData reportData, Object obj)
		throws ReportException {
		reportData.setContextData(obj);

		super.execute(reportData);
	}

	/**
	 * @return
	 */
	public int getEnd() {
		return end;
	}

	/**
	 * @return
	 */
	public int getStart() {
		return start;
	}

	/**
	 * @param i
	 */
	public void setEnd(int i) {
		end = i;
	}

	/**
	 * @param i
	 */
	public void setStart(int i) {
		start = i;
	}

}
